<#include "/includes/vars.inc"> 
<@pp.dropOutputFile />
<#assign fileName = "${javaDir}${packageDir}/web/listener/LoginPhaseListener.java">
<#if includeLoginJsf && !pp.outputFileExists(fileName)>
	<@pp.changeOutputFile name="${fileName}" />
		
package ${project.@rootPackage}.web.listener;

import ${project.@rootPackage}.web.util.JsfUtil;
import ${project.@rootPackage}.web.support.LoginController;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;


/**
 * <#if project.@author[0]??>@author ${project.@author}</#if>
 */
public class LoginPhaseListener implements PhaseListener {

    private static final long serialVersionUID = 1L;

    @Override
    public void afterPhase(PhaseEvent event) {
        //Logger.getLogger(this.getClass().getName()).log(Level.INFO, "AP:{0}", event.getPhaseId());
        String viewid = event.getFacesContext().getViewRoot().getViewId();

        if (!loggedIn() && ! (viewid.equals("/index.xhtml") || viewid.equals("/login.xhtml") )){
            //not logged
            JsfUtil.redirect("/login.jsf");
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        //Logger.getLogger(this.getClass().getName()).log(Level.INFO, "BF:{0}", event.getPhaseId());
    }

    private boolean loggedIn() {
        LoginController log = (LoginController) JsfUtil.getBean("loginController");
        if (log != null) {
            if (log.isLoggedIn()) {
                return true;
            }
        }
        return false;
    }

    private boolean isRoleAdmin() {
        LoginController log = (LoginController) JsfUtil.getBean("loginController");
        if (log != null) {
            if (log.isRoleAdmin()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

}
</#if>
